﻿using Abp.Collections.Extensions;
using FutureApp.Authorization;
using FutureApp.Authorization.Permissions;
using FutureApp.EntityFramework;
using System.Collections.Generic;
using System.Linq;

namespace FutureApp.Migrations.SeedData
{
    public class DefaultPermissionDefinitionCreator
    {
        public static List<PermissionDefinition> InitialPermissionDefinitions { get; private set; }

        static DefaultPermissionDefinitionCreator()
        {
            InitialPermissionDefinitions = new List<PermissionDefinition>
            {
                new PermissionDefinition
                {
                    Code = PermissionNames.Pages,
                    Name = "基本页面",
                    Children = new List<PermissionDefinition>
                    {
                        new PermissionDefinition
                        {
                            Code = PermissionNames.Pages_Tenants,
                            Name = "租户管理页面",
                        },
                        new PermissionDefinition
                        {
                            Code = PermissionNames.Pages_Users,
                            Name = "用户管理页面",
                        },
                        new PermissionDefinition
                        {
                            Code = PermissionNames.Pages_Roles,
                            Name = "角色管理页面",
                        },
                        new PermissionDefinition
                        {
                            Code = PermissionNames.Pages_Permissions,
                            Name = "权限管理页面",
                        },
                        new PermissionDefinition
                        {
                            Code = PermissionNames.Pages_Goods,
                            Name = "商品管理页面",
                        },
                    }
                }

            };
        }

        private readonly FutureAppDbContext _context;
        public DefaultPermissionDefinitionCreator(FutureAppDbContext context)
        {
            this._context = context;
        }

        public void Create()
        {
            InitialPermissionDefinitions.ForEach(this.AddIfNotExists);
            this._context.SaveChanges();
        }

        private void AddIfNotExists(PermissionDefinition def)
        {
            if (!this._context.PermissionDefinitions.Any(s => s.Code == def.Code))
            {
                this._context.PermissionDefinitions.Add(def);
            }
            if (!def.Children.IsNullOrEmpty())
            {
                def.Children.ToList().ForEach(m =>
                {
                    var existedEntity = this._context.PermissionDefinitions.FirstOrDefault(s => s.Code == def.Code);
                    m.ParentId = (existedEntity ?? def).Id;
                    this.AddIfNotExists(m);
                });
            }
        }
    }
}
